<?php

class loginController extends Controller {

    public $initphp_list = array(
        'run',
        'login',
        'logout',
        'validcode'
    );

    public function __construct() {
        parent::__construct();
    }

    public function run() {
        $this->view->assign("menu_now", "users");
        $this->view->set_tpl("manage/login");
        $this->view->display();
    }

    /**
     * 登陆
     */
    public function login() {
        $info = $this->controller->get_gp(array(
            'username',
            'password',
            'validcode',
        ));
        $session = $this->getUtil('session');
        $code = $session->get('user_vaildcode_key');
        if (strtolower(trim($code)) !== strtolower(trim($info['validcode']))) {
            $data = array(
                'status' => 0,
                'message' => "验证码错误！"
            );
        } else {
            $password = md5($info['password']);
            $admin = InitPHP::getService("admin");
            $result = $admin->getOneByName($info['username']);
            if (!$result){
                $result=$admin->getOneByEmail($info['username']);
            }
            if ($result) {
                if ($result['pass'] === $password) {
                    $update['last_login_time']=time();
                    $update['last_ip']=InitPHP::getLibrarys("ip")->get_ip();
                    $admin->update($result['id'],$update);
                    $session->set('adminid', intval($result['id']));
                    $session->set('adminname', htmlspecialchars($info['username']));
                    $data = array(
                        'status' => 1
                    );
                } else {
                    $data = array(
                        'status' => 0,
                        'message' => "密码错误！"
                    );
                }
            } else {
                $data = array(
                    'status' => 0,
                    'message' => "用户不存在！"
                );
            }
        }
        echo json_encode($data);
    }
    /**
     * 获取验证码函数
     */
    public function validcode() {
        $captcha = self::getValid();
        $code = $captcha->RandRSI();
        $session = $this->getUtil('session');
        $session->set('user_vaildcode_key', $code);
        $captcha->Draw();
    }

    /**
     *
     * @return vaildInit
     */
    private function getValid() {
        return InitPHP::getLibrarys("vaild");
    }

}